﻿using Dt261.jsonmodel;
using Dt261.Model;
using Dt261.ViewModel;
using Panuon.UI.Silver;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Printing;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;



namespace Dt261.Views
{
    /// <summary>
    /// PreviewSpeechPage.xaml 的交互逻辑
    /// </summary>
    public partial class PreviewSpeechPage : Page
    {
        public PreviewSpeechPage(SpeechResultItem result, MemberInfo member)
        {
            InitializeComponent();


            PreviewSpeechViewModel model = new PreviewSpeechViewModel(result, member);
            this.DataContext = model;
        }

        private FixedDocument dixd;

        void export(bool print)
        {
            //var fixedDoc = new FixedDocument();
            //var pageContent = new PageContent();
            //var fixedPage = new FixedPage();

            //fixedPage.Children.Add(canvas);
            //((IAddChild)pageContent).AddChild(fixedPage);
            //fixedDoc.Pages.Add(pageContent);

            //using var xpsd = new XpsDocument(@"r:\3.xps", FileAccess.ReadWrite);
            //var xw = XpsDocument.CreateXpsDocumentWriter(xpsd);

            //xw.Write(fixedDoc);
            //xpsd.Close();
            var basePath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            var path = System.IO.Path.Combine(basePath, "言语测试_" + DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".png");

            var model = DataContext as PreviewSpeechViewModel;

            SavePIC(path, model.CurrentIndex == 0 ? docContent : docContent2, PICType.PNG, print);


        }


        private FixedDocument FD;

        public void AddPage(Visual V)
        {
            FrameworkElement FE = V as FrameworkElement;
            FixedPage FP = new FixedPage();
            FP.Width = FE.ActualWidth; //可用FE.Width替换
            FP.Height = FE.ActualHeight; //可用FE.Height替换
            FP.Children.Add(FE);
            PageContent pageContent = new PageContent();
            pageContent.Child = FP;
            FD.Pages.Add(pageContent);
        }

  void save(string path)
        {
            //var fixedDoc = new FixedDocument();
            //var pageContent = new PageContent();
            //var fixedPage = new FixedPage();

            //fixedPage.Children.Add(canvas);
            //((IAddChild)pageContent).AddChild(fixedPage);
            //fixedDoc.Pages.Add(pageContent);

            //using var xpsd = new XpsDocument(@"r:\3.xps", FileAccess.ReadWrite);
            //var xw = XpsDocument.CreateXpsDocumentWriter(xpsd);

            //xw.Write(fixedDoc);
            //xpsd.Close();
    
            var model = DataContext as PreviewPageViewModel;

            SavePIC(path, model.CurrentIndex == 0 ? docContent : docContent2, PICType.PNG, false);


        }

        private void SavePIC(string TempPath, Visual V, PICType PT, bool print)
        {
            FrameworkElement FE = V as FrameworkElement;


            ScrollViewer sv = V as ScrollViewer;

            var item = sv.Content as Grid;
            var width = item.RenderSize.Width;
            var height = item.RenderSize.Height;

            var drawingV = new DrawingVisual();
            var drawingB = new VisualBrush(item);

            using (var context = drawingV.RenderOpen())
            {
                context.DrawRectangle(drawingB, null, new Rect(new Point(0, 0), new Size(width,
                                                       height)));
            }
            RenderTargetBitmap RTB = new RenderTargetBitmap(
                                           (int)width,
                                           (int)height,
                                           96.0,
                                           96.0,

                                           PixelFormats.Pbgra32);

            RTB.Render(drawingV);
            System.Windows.Clipboard.SetImage(RTB);

            if (print)
            {

                //PrintDialog diag = new PrintDialog();

                var printDialog = new System.Windows.Controls.PrintDialog();

                //设置纸张大小
                var pageWidth = (int)Math.Ceiling(printDialog.PrintableAreaWidth);
                var pageHeight = (int)Math.Ceiling(printDialog.PrintableAreaHeight);

                printDialog.PrintTicket.PageMediaSize = new PageMediaSize(pageWidth, pageHeight);

                //打印
                //printDialog.PrintVisual(userControl, description);//

                //
                if (printDialog.ShowDialog() == true)
                {
                    printDialog.PrintVisual(V, TempPath);
                }
                return;
            }

            BitmapEncoder BE = new BmpBitmapEncoder();

            switch (PT)
            {
                case PICType.PNG:
                    BE = new PngBitmapEncoder();
                    break;
                case PICType.JPG:
                    BE = new JpegBitmapEncoder();
                    break;
                case PICType.BMP:
                    BE = new BmpBitmapEncoder();
                    break;
                case PICType.GIF:
                    BE = new GifBitmapEncoder();
                    break;
                case PICType.TIFF:
                    BE = new TiffBitmapEncoder();
                    break;
                default:
                    BE = new BmpBitmapEncoder();
                    break;
            }
            GifBitmapEncoder a = new GifBitmapEncoder();
            BE?.Frames.Add(BitmapFrame.Create(RTB));
            using (FileStream fs = File.Open(TempPath, FileMode.OpenOrCreate))
            {
                BE.Save(fs);
            }

           //if (print)
           // {
           //     PrintImage(TempPath);
           // }
           // else
                Notice.Show("图片已保存到" + TempPath, "提示", 3, Panuon.UI.Silver.MessageBoxIcon.Success);
        }


        /// <summary>
        /// 根据用户控件列表创建文档
        /// </summary>
        /// <param name="list"></param>
        //public void CreateDocument(List<System.Windows.Controls.UserControl> list)
        //{
        //    FixedDocument fixedDoc = new FixedDocument();
        //    foreach (var item in list)
        //    {
        //        PageContent pageContent = new PageContent();
        //        FixedPage fixedPage = new FixedPage();

        //        //如果有需要可以对page进行旋转
        //        //fixedPage.RenderTransformOrigin = new Point(0.5, 0.37);
        //        //RotateTransform rotateTransform = new RotateTransform();
        //        //rotateTransform.Angle = 90;
        //        //fixedPage.RenderTransform = rotateTransform;
        //        fixedPage.HorizontalAlignment = Left;
        //        fixedPage.VerticalAlignment = VerticalAlignment.Top;
        //        fixedPage.Children.Add(item);
        //        double pageWidth = 96 * 8.5;
        //        double pageHeight = 96 * 11;

        //        //由于要横向展示，所以高度和宽度进行调换
        //        fixedPage.Width = pageHeight + 60;
        //        fixedPage.Height = pageWidth;
        //        ((IAddChild)pageContent).AddChild(fixedPage);
        //        fixedDoc.Pages.Add(pageContent);
        //    }
        //    dixd = fixedDoc;
        //}


        //private void PrintImage(string outputPath)
        //{
        //    try
        //    {
        //        this.Cursor = Cursors.Wait;
        //        var bi = new BitmapImage();
        //        bi.BeginInit();
        //        bi.CacheOption = BitmapCacheOption.OnLoad;
        //        //加载图片
        //        bi.UriSource = new Uri(outputPath);
        //        bi.EndInit();

        //        var vis = new DrawingVisual();
        //        using (var dc = vis.RenderOpen())
        //        {
        //            dc.DrawImage(bi, new Rect { Width = bi.Width, Height = bi.Height });
        //        }

        //        var pdialog = new PrintDialog();
        //        if (pdialog.ShowDialog() == true)
        //        {
        //            pdialog.PrintVisual(vis, "My Image");
        //        }
        //    }
        //    finally
        //    {
        //        this.Cursor = Cursors.AppStarting;
        //    }
        //}
        //public void Print(UserControl userControl, bool rorate90, string printer, int copyCount)
        //{
        //    //旋转
        //    if (rorate90)
        //    {
        //        var rotateTransform = new RotateTransform(90);
        //        userControl.LayoutTransform = rotateTransform;
        //    }

        //    //刷新UI
        //    var size = rorate90
        //        ? new Size(userControl.Width, userControl.Height)
        //        : new Size(userControl.Height, userControl.Width);
        //    userControl.Measure(size);
        //    userControl.Arrange(new Rect(new Point(0, 0), size));

        //    //设置对齐方式
        //    userControl.HorizontalAlignment = HorizontalAlignment.Left;
        //    userControl.VerticalAlignment = VerticalAlignment.Top;

        //    //更新布局
        //    userControl.UpdateLayout();

        //    //开始打印
        //    Print(userControl, printer, "test print", copyCount);
        //}

        ///// <summary>
        ///// 打印
        ///// </summary>
        ///// <param name="userControl">要打印的控件</param>
        ///// <param name="printer">打印机名称</param>
        ///// <param name="description">打印描述</param>
        ///// <param name="copyCount">打印个数</param>
        //public static void Print(UserControl userControl, string printer, string description, int copyCount)
        //{



        //    var printDialog = new PrintDialog();

        //    //设置纸张大小
        //    var pageWidth = (int)Math.Ceiling(printDialog.PrintableAreaWidth);
        //    var pageHeight = (int)Math.Ceiling(printDialog.PrintableAreaHeight);

        //    printDialog.PrintTicket.PageMediaSize = new PageMediaSize(pageWidth, pageHeight);

        //    //打印
        //    printDialog.PrintVisual(userControl, description);
        //}

        private RenderTargetBitmap GetPIC(Visual V)
        {
            FrameworkElement FE = V as FrameworkElement;

            var item = V as Canvas;
            var width = item.RenderSize.Width;
            var height = item.RenderSize.Height;

            var drawingV = new DrawingVisual();
            var drawingB = new VisualBrush(item);

            using (var context = drawingV.RenderOpen())
            {
                context.DrawRectangle(drawingB, null, new Rect(new Point(0, 0), new Size(width,
                                                       height)));
            }
            RenderTargetBitmap RTB = new RenderTargetBitmap(
                                           (int)width * 2,
                                           (int)height * 2,
                                           96.0 * 2,
                                           96.0 * 2,

                                           PixelFormats.Pbgra32);

            RTB.Render(drawingV);

            return RTB;

        }


        enum PICType
        {
            PNG = 0,
            JPG = 1,
            BMP = 2,
            GIF = 3,
            TIFF = 4

        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            //设置文件类型
            sfd.Filter = "(*.png)|*.png";

            //设置默认文件类型显示顺序
            sfd.FilterIndex = 1;

            //保存对话框是否记忆上次打开的目录
            sfd.RestoreDirectory = true;

            sfd.FileName = "言语测试" + DateTime.Now.ToString("yyyyMMdd");

            //点了保存按钮进入
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                string localFilePath = sfd.FileName.ToString(); //获得文件路径
                string fileNameExt = localFilePath.Substring(localFilePath.LastIndexOf("\\") + 1); //获取文件名，不带路径

                //获取文件路径，不带文件名
                //FilePath = localFilePath.Substring(0, localFilePath.LastIndexOf("\\"));

                //给文件名前加上时间
                //newFileName = DateTime.Now.ToString("yyyyMMdd") + fileNameExt;

                //在文件名里加字符
                //saveFileDialog1.FileName.Insert(1,"dameng");

                //System.IO.FileStream fs = (System.IO.FileStream)sfd.OpenFile();//输出文件

                ////fs输出带文字或图片的文件，就看需求了
                ///
                save(localFilePath);
            }
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            export(true);

            //CreateDocument();
            //PrintDialog printDialog = new PrintDialog();
            //if (printDialog.ShowDialog() == true)
            //{
            //    //printDialog.PrintTicket.PageOrientation = PageOrientation.Landscape;
            //    printDialog.PrintTicket.Duplexing = Duplexing.TwoSidedShortEdge;
            //    printDialog.PrintDocument(dixd.DocumentPaginator, "测试报告");
            //}
        }
        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            DMSkin.Core.Broadcast.PushBroadcast("NavigationBack", "PreviewPage");
        }

    }
}
